package com.my.code.threadpool;

import java.util.Random;
import java.util.concurrent.*;

/**
 * <b>测试定时任务的取消</b><p>
 *
 * @author zzl
 * @date 2020/11/2
 */
public class TestScheduleFuture {

    private static final ScheduledExecutorService es = Executors.newScheduledThreadPool(9);
    private static final ConcurrentHashMap<Integer, ScheduledFuture> cache = new ConcurrentHashMap<>();

    public static void main(String[] args) throws InterruptedException {

        int len = 10;
        Random r = new Random();

        for (int i = 0; i < len; i++) {
            int finalI = i;
            ScheduledFuture<?> future = es.schedule(() -> System.out.println(Thread.currentThread().getName() + " execute i = " + finalI), r.nextInt(60) + 1, TimeUnit.SECONDS);
            cache.put(i, future);
        }

        TimeUnit.SECONDS.sleep(1);

        for (int i = 0; i < len; i++) {
            boolean cancel = cache.get(i).cancel(false);
            System.out.println("cancel task i = " + i + " ,result = " + cancel);//可以正常取消
        }

        System.out.println("cancel, done");
    }

}
